import { FC, useState } from 'react';
import { Button, message, Modal } from 'antd';
import styles from './minerLogModal.module.less';
import useSwr from 'swr';
import { fetchMinerLog } from '@/service/log';
import Ansi from 'ansi-to-react';
interface ITaskModalProps {
  visible: boolean;
  setVisible: (flag: boolean) => void;
  mid: number;
  miners: string[];
}

// 监控端连接超时，请稍后重试
// 监控端连接失败，正在尝试重新连接

const MinerLogModal: FC<ITaskModalProps> = (props) => {
  const { visible, setVisible, mid, miners } = props;

  const [isRefreshInterval, setIsRefreshInterval] = useState(true);
  const [logStack, setLogStack] = useState<
    {
      type: 'success' | 'error';
      detail: string;
      timestamp?: number;
    }[]
  >([]);

  useSwr(
    visible ? ['/log', mid, miners[0]] : null,
    (url, mid, mac) => fetchMinerLog(mid, mac),
    {
      refreshInterval: isRefreshInterval && visible ? 4500 : 0,
      shouldRetryOnError: false,
      onError(e) {
        setLogStack((log) => {
          return log.concat({
            type: 'error',
            detail: '监控端连接失败，正在尝试重新连接',
          });
        });
        const errCount = logStack.filter((log) => log.type === 'error');
        if (errCount && errCount.length >= 2) {
          setIsRefreshInterval(false);
          setLogStack((log) => {
            return log.concat({
              type: 'error',
              detail: '监控端连接超时，请稍后重试',
              timestamp: Date.now(),
            });
          });
        }
      },
      onSuccess(data) {
        setLogStack((log) => {
          if (
            log.length == 0 ||
            log[log.length - 1].timestamp !== data[0].timestamp
          ) {
            return log.concat(data);
          }
          return log;
        });
      },
    },
  );

  const handleCancel = () => {
    setIsRefreshInterval(false);
    setVisible(false);
  };

  return (
    <Modal
      title="矿机日志"
      centered
      visible={props.visible}
      destroyOnClose={true}
      onCancel={handleCancel}
      footer={null}
      afterClose={handleCancel}
      bodyStyle={{ padding: '0' }}
    >
      <div className={`${styles.logAppend}`}>
        {logStack &&
          logStack.map((a, index) => {
            return (
              <Ansi key={`${index}-${a.timestamp}`}>
                {a.timestamp ? a.detail : '连接监控端成功...'}
              </Ansi>
            );
          })}
        <div className={styles.flashCursor}></div>
      </div>
    </Modal>
  );
};

export default MinerLogModal;
